package com.iterator.typeHandler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;


/**
 * @author tean_cy
 * @date 2021/1/10 11:06
 */
@MappedTypes(List.class)
public class StringToListTypeHandler extends BaseTypeHandler<List<String>> {
    // objectMapper 通过该对象调用方法
    ObjectMapper objectMapper = new ObjectMapper();

    /**
     * setNonNullParameter 方法将java对应的数据类型转换为json字符串，写到数据库中
     */
    @SneakyThrows
    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, List<String> strings, JdbcType jdbcType) throws SQLException {
        String s = objectMapper.writeValueAsString(strings);
        preparedStatement.setString(i,s);
    }

    /**
     *
     * @param resultSet 所有的字段名的信息
     * @param columnLabel  具体需要转换的字段名
     * @return
     * @throws SQLException
     */
    @Override
    public List<String> getNullableResult(ResultSet resultSet, String columnLabel) throws SQLException {
        String value = resultSet.getString(columnLabel);
        if (value == null){
            return null;
        }
        List<String> list = null;
        try {
            list = objectMapper.readValue(value, List.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return list;
    }

    @Override
    public List<String> getNullableResult(ResultSet resultSet, int i) throws SQLException {
        return null;
    }

    @Override
    public List<String> getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        return null;
    }
}
